﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;

namespace PythonInvokerTest
{
    /// <summary>
    /// 用于保存各类常用函数。
    /// </summary>
    public class funs
    {
        public static void SimpleInvoke()
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = @"python.exe";
            p.StartInfo.Arguments = @"C:\Program Files\Test D:\Output";
            p.Start();
        }

        public static Task<string> ReturnableInvoke(string pypath, string arguments)
        {
            var t = Task.Run(() =>
              {
                  System.Diagnostics.Process p = new System.Diagnostics.Process();
                  p.StartInfo.FileName = @"python.exe";
                  p.StartInfo.Arguments = $"{pypath} {arguments}";
                  p.StartInfo.UseShellExecute = false; // 必需设置此属性为true，下面两个属性才有效
                  p.StartInfo.RedirectStandardOutput = true; // 关键行2
                  p.StartInfo.CreateNoWindow = true;
                  p.Start();
                  return p.StandardOutput.ReadToEnd();
              });
            return t;
        }

        public static string SelectFile(string path)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "*.py|*.py|所有文件(*.*)|*.*";
            ofd.FileName = File.Exists(path) ? path : System.IO.Path.GetFullPath(".");
            ofd.InitialDirectory = File.Exists(path) ? Path.GetDirectoryName(path) : System.IO.Path.GetFullPath(".");
            ofd.ShowDialog();
            //if (ofd.ShowDialog() == DialogResult.OK) { }

            return ofd.FileName;
        }

        public static string[] ReadPyscriptInfo(string path)
        {
            if (!File.Exists(path))
                return null;

            var rets = new List<string>();

            var texts = File.ReadAllLines(path, Encoding.UTF8);

            /*
             if __name__ == "__main__":
                parser = argparse.ArgumentParser(description="Sample CSV file and save to another CSV.")
                parser.add_argument("input_csv", type=str, help="Path to the input CSV file.")
                parser.add_argument("output_csv", type=str, help="Path to the output CSV file.")
                parser.add_argument("--sample_size", type=int, default=10000,
                                    help="Number of rows to sample from the input CSV (default: 10000).")
                args = parser.parse_args()
                sample_csv_to_csv(args.input_csv, args.output_csv, args.sample_size)
             */

            List<string> lines = new List<string>();
            for (int i = 0; i < texts.Length; i++)
                if (texts[i].Trim() is string line && line.StartsWith("#"))
                    lines.Add(line);

            for (int i = 0; i < texts.Length; i++)
            {
                var si = texts[i];
                // 查找函数说明 ArgumentParser
                if (si.Contains("ArgumentParser"))
                {
                    int current_lineno = i;
                    string temp = si;
                    List<string> list = new List<string>();
                    list.Add(temp);
                    while (!temp.EndsWith(")"))
                    {
                        current_lineno++;
                        if (current_lineno == texts.Length - 1)
                            break;
                        temp = texts[current_lineno];
                        list.Add(temp);
                    }
                    string str = string.Join("", list.ToArray()).Trim();
                    rets.Add(str.Replace("argparse.ArgumentParser", "~").Split('~')[1].Trim('(', ')'));
                    continue;
                }

                // 查找参数说明 add_argument
                if (si.Contains("add_argument"))
                {
                    int current_lineno = i;
                    string temp = si;
                    List<string> list = new List<string>();
                    list.Add(temp);
                    while (!temp.EndsWith(")"))
                    {
                        current_lineno++;
                        if (current_lineno == texts.Length - 1)
                            break;
                        temp = texts[current_lineno].Trim();
                        list.Add(temp);
                    }
                    string str = string.Join("", list.ToArray()).Trim();
                    rets.Add(str.Replace("parser.add_argument", "").Trim('(', ')'));
                    continue;
                }
            }

            return rets.ToArray();

        }

        /// <summary>
        /// 路径转字符串中需要转义的字符串。
        /// </summary>
        public static string[] EscapingPathStrings = { ":>", "\\", "/", "\'", "\"", ">" };

        /// <summary>
        /// NameString是指不包括EscapingPathStrings的路径字符串。
        /// 文件路径转文件名，根据EscapingPathStrings的值转为下划线。
        /// 相对路径会自动转换为全路径。输入路径直接取全路径，同时null会转为长度为0的字符串。
        /// </summary>
        /// <param name="filepath">输入路径。</param>
        /// <returns></returns>
        public static string PathToNameString(string filepath)
        {
            if (!string.IsNullOrEmpty(filepath))
            {
                var abspath = Path.GetFullPath((filepath + "").Trim());
                foreach (string s in EscapingPathStrings)
                    abspath = abspath.Replace(s, "_");
                return abspath;
            }
            return "";
        }

        /// <summary>
        /// 2024/05/30 测试可用。参考：https://blog.csdn.net/lzl_li/article/details/117038323
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static System.Drawing.Icon GetIconFromFile(string fileName)
        {
            if (System.IO.File.Exists(fileName) == false)
                return null;
            return System.Drawing.Icon.ExtractAssociatedIcon(fileName);
        }
    }
}
